package org.hcyspartnoc.demo.utils;

import org.springframework.util.DigestUtils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Random;

public class StringUtils {

    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String encodeByMd5(String data, String salt) {
        String newData = data + salt;
        return DigestUtils.md5DigestAsHex(newData.getBytes());
    }

    public static String encodeByMd5(String data) {
        return DigestUtils.md5DigestAsHex(data.getBytes());
    }

    public static String randomStr(int length) {
        Random random = new Random(System.currentTimeMillis());
        char randNum = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            switch (randNum % 3) {
                case 0 -> randNum = (char) random.nextInt(65, 91);
                case 1 -> randNum = (char) random.nextInt(97, 123);
                case 2 -> randNum = (char) random.nextInt(48, 58);
            }
            sb.append(randNum);
        }
        return sb.toString();
    }

    public static String randomNumStr(int length) {
        Random random = new Random(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(0, 10));
        }
        return sb.toString();
    }

    public static String formatDateTime(LocalDateTime dateTime) {
        if (dateTime == null) {
            return null;
        }
        return dateTime.format(df);
    }

    public static LocalDateTime parseDateTime(String timestampStr) {
        // 假设这是你的时间戳（毫秒）
        long timestamp = Long.parseLong(timestampStr);
        // 使用Instant类
        Instant instant = Instant.ofEpochMilli(timestamp);
//        // 如果你想要的是UTC时间
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("UTC"));
//        String utcString = instant.atZone(ZoneId.of("UTC")).format(formatter);
//        System.out.println("UTC Time: " + utcString);
        // 如果你想要的是本地时间
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static LocalDateTime parseDateTime_2(String formatTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
        // 将字符串转换为OffsetDateTime
        OffsetDateTime offsetDateTime = OffsetDateTime.parse(formatTime, formatter);
        // 使用特定的时区（在这个例子中是东八区）来获取ZonedDateTime
        ZoneId zoneId = ZoneId.of("Asia/Shanghai"); // 东八区的一个代表时区
        ZonedDateTime zonedDateTime = offsetDateTime.atZoneSameInstant(zoneId);
        // 如果你确实需要LocalDateTime（比如与某些API兼容），可以这样做
        // 但请注意，这将丢失时区信息
        return zonedDateTime.toLocalDateTime();
    }


}
